//
//  AVTools.m
//  MySounds
//
//  Created by 李钰 on 2017/9/19.
//  Copyright © 2017年 tianhuangyule. All rights reserved.
//

#import "AVTools.h"
#import <AVFoundation/AVFoundation.h>
#define kFileManager [NSFileManager defaultManager]
@interface AVTools()<AVAudioPlayerDelegate>
@property (nonatomic, strong) NSString * filePath;
@property (nonatomic, strong) AVAudioPlayer * player;
@property (nonatomic, strong) NSMutableArray * soundsArr;
@end
@implementation AVTools
{

}
+ (AVTools *)sharedInstance {
    static id avTools = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        avTools = [[self alloc] init];
    });
    return avTools;
}
- (void)playSoundsWithString:(NSString *)string
{
    NSMutableArray * soundsArr = [NSMutableArray new];
    
    if ([string hasPrefix: @"收银成功"] && [string hasSuffix: @"元"]) {
        
        NSString * audioPath = [self getPathWithName: @"收银成功"];
        [soundsArr addObject: audioPath];
        NSString * newString = [string stringByReplacingOccurrencesOfString: @"收银成功" withString: @""];
        newString = [newString stringByReplacingOccurrencesOfString: @"元" withString: @""];
        if([newString rangeOfString: @"."].location != NSNotFound){//有小数点
            NSArray * source = [newString componentsSeparatedByString: @"."];
            [soundsArr addObjectsFromArray: [self getSoundsWithString: [source firstObject] AndDotEnd: NO]];
            NSString * lastString = [source lastObject];
            if ([lastString integerValue] != 0) {
                [soundsArr addObject: [self getPathWithName: @"dot"]];
                [soundsArr addObjectsFromArray: [self getSoundsWithString: [source lastObject] AndDotEnd: YES]];
            }
        }else{//整数
            [soundsArr addObjectsFromArray: [self getSoundsWithString: newString AndDotEnd: NO]];
        }
        [soundsArr addObject: [self getPathWithName: @"yuan"]];
        [self connectPathArr: soundsArr];
    }
}
//dotEnd 小数点后面的数字
- (NSArray *)getSoundsWithString:(NSString *)string AndDotEnd:(BOOL)dotEnd
{
    NSMutableArray * source = [NSMutableArray new];
    if (dotEnd) {
        for(int i=0; i < [string length]; i++)
        {
            NSString * temp = [string substringWithRange:NSMakeRange(i, 1)];
            [source addObject: [self getPathWithName: temp]];
        }
        return source;
    }
    switch (string.length) {
        case 1://个位
        {
            [source addObject: [self getPathWithName: string]];
        }
            break;
        case 2://十位
        {
            NSString * temp = [string substringWithRange: NSMakeRange(0, 1)];
            if ([temp integerValue] !=0) {
                [source addObject: [self getPathWithName: temp]];
                [source addObject: [self getPathWithName: @"ten"]];
                temp = [string substringWithRange: NSMakeRange(1, 1)];
                if ([temp integerValue] !=0) {
                    [source addObject: [self getPathWithName: temp]];
                }
            }
            
        }
            break;
        case 3://百位
        {
            NSString * temp = [string substringWithRange: NSMakeRange(0, 1)];
            if ([temp integerValue] !=0) {
                [source addObject: [self getPathWithName: temp]];
                [source addObject: [self getPathWithName: @"hundred"]];
                if ([string integerValue]%100 == 0) {
                    return source;
                }
                temp = [string substringWithRange: NSMakeRange(1, 1)];
                [source addObject: [self getPathWithName: temp]];
                if ([temp integerValue] !=0) {
                    [source addObject: [self getPathWithName: @"ten"]];
                }
                temp = [string substringWithRange: NSMakeRange(2, 1)];
                if ([temp integerValue] !=0) {
                    [source addObject: [self getPathWithName: temp]];
                }
            }
        }
            break;
        case 4://千位
        {
            BOOL hundredZero = NO;
            NSString * temp = [string substringWithRange: NSMakeRange(0, 1)];
            if ([temp integerValue] !=0) {
                [source addObject: [self getPathWithName: temp]];
                [source addObject: [self getPathWithName: @"thousand"]];
                if ([string integerValue]%1000 == 0) {
                    return source;
                }
                temp = [string substringWithRange: NSMakeRange(1, 1)];
                [source addObject: [self getPathWithName: temp]];
                if ([temp integerValue] !=0) {
                    [source addObject: [self getPathWithName: @"hundred"]];
                }else{
                    hundredZero = YES;
                }
                temp = [string substringWithRange: NSMakeRange(2, 1)];
                [source addObject: [self getPathWithName: temp]];
                if ([temp integerValue] !=0) {
                    [source addObject: [self getPathWithName: @"ten"]];
                }else if(hundredZero){//说明前面有念零
                    [source removeLastObject];
                }
                temp = [string substringWithRange: NSMakeRange(3, 1)];
                if ([temp integerValue] !=0) {
                    [source addObject: [self getPathWithName: temp]];
                }else {
                    NSString * lastString = [source lastObject];
                    if ([lastString hasSuffix: @"0.wav"]) {
                        [source removeLastObject];
                    }
                }
            }
        }
            break;
        case 5://万位
        {
            BOOL tousandZero = NO;
            BOOL hundredZero = NO;
            NSString * temp = [string substringWithRange: NSMakeRange(0, 1)];
            if ([temp integerValue] !=0) {
                [source addObject: [self getPathWithName: temp]];
                [source addObject: [self getPathWithName: @"ten_thousand"]];
                if ([string integerValue]%10000 == 0) {
                    return source;
                }
                temp = [string substringWithRange: NSMakeRange(1, 1)];
                [source addObject: [self getPathWithName: temp]];
                if ([temp integerValue] !=0) {
                    [source addObject: [self getPathWithName: @"thousand"]];
                }else{
                    tousandZero = YES;
                }
                temp = [string substringWithRange: NSMakeRange(2, 1)];
                [source addObject: [self getPathWithName: temp]];
                if ([temp integerValue] !=0) {
                    [source addObject: [self getPathWithName: @"hundred"]];
                }else{
                    if (tousandZero) {
                        [source removeLastObject];
                    }
                    hundredZero = YES;
                }
                temp = [string substringWithRange: NSMakeRange(3, 1)];
                [source addObject: [self getPathWithName: temp]];
                if ([temp integerValue] !=0) {
                    [source addObject: [self getPathWithName: @"ten"]];
                }else{//说明前面有念零
                    if (hundredZero) {
                        [source removeLastObject];
                    }
                }
                temp = [string substringWithRange: NSMakeRange(4, 1)];
                if ([temp integerValue] !=0) {
                    [source addObject: [self getPathWithName: temp]];
                }else {
                    NSString * lastString = [source lastObject];
                    if ([lastString hasSuffix: @"0.wav"]) {
                        [source removeLastObject];
                    }
                }
            }
        }
            break;
        case 6://十万位
        {
            BOOL tousandZero = NO;
            BOOL hundredZero = NO;
            NSString * temp = [string substringWithRange: NSMakeRange(0, 1)];
            if ([temp integerValue] !=0) {
                [source addObject: [self getPathWithName: temp]];
                [source addObject: [self getPathWithName: @"ten"]];
                if ([string integerValue]%100000 == 0) {
                    [source addObject: [self getPathWithName: @"ten_thousand"]];
                    return source;
                }
                temp = [string substringWithRange: NSMakeRange(1, 1)];
                if ([temp integerValue] !=0) {
                    [source addObject: [self getPathWithName: temp]];
                }
                [source addObject: [self getPathWithName: @"ten_thousand"]];
                
                temp = [string substringWithRange: NSMakeRange(2, 1)];
                [source addObject: [self getPathWithName: temp]];
                if ([temp integerValue] !=0) {
                    [source addObject: [self getPathWithName: @"thousand"]];
                }else{
                    tousandZero = YES;
                }
                temp = [string substringWithRange: NSMakeRange(3, 1)];
                [source addObject: [self getPathWithName: temp]];
                if ([temp integerValue] !=0) {
                    [source addObject: [self getPathWithName: @"hundred"]];
                }else{
                    if (tousandZero) {
                        [source removeLastObject];
                    }
                    hundredZero = YES;
                }
                temp = [string substringWithRange: NSMakeRange(4, 1)];
                [source addObject: [self getPathWithName: temp]];
                if ([temp integerValue] !=0) {
                    [source addObject: [self getPathWithName: @"ten"]];
                }else{//说明前面有念零
                    if (hundredZero) {
                        [source removeLastObject];
                    }
                }
                temp = [string substringWithRange: NSMakeRange(5, 1)];
                if ([temp integerValue] !=0) {
                    [source addObject: [self getPathWithName: temp]];
                }else {
                    NSString * lastString = [source lastObject];
                    if ([lastString hasSuffix: @"0.wav"]) {
                        [source removeLastObject];
                    }
                }
            }
        }
            break;
        default:
            break;
    }
    return source;
}
- (NSString *)getPathWithName:(NSString *)name
{
    NSString * path =  [[NSBundle mainBundle] pathForResource: name ofType:@"wav"];
    return path;
}
- (void)connectPathArr:(NSArray *)pathArr
{
    AVMutableComposition *composition = [AVMutableComposition composition];
    CMTime time = kCMTimeZero;
    for (NSString * path in pathArr) {
        
        AVURLAsset *audioAsset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath: path]];
        
        // 音频通道
        AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:0];
        
        // 音频采集通道
        AVAssetTrack * audioAssetTrack = [[audioAsset tracksWithMediaType:AVMediaTypeAudio] firstObject];
        
        // 音频合并 - 插入音轨文件
        [audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset.duration) ofTrack: audioAssetTrack atTime:time error:nil];
        time = CMTimeAdd(time, audioAsset.duration);
        
        // `startTime`参数要设置为第一段音频的时长，即`audioAsset1.duration`, 表示将第二段音频插入到第一段音频的尾部。
    }
    AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset: composition presetName:AVAssetExportPresetAppleM4A];
    NSInteger currentTime = (NSInteger)[[NSDate date] timeIntervalSince1970];
    NSString * outPutFilePath = [[self.filePath stringByDeletingLastPathComponent] stringByAppendingPathComponent: [NSString stringWithFormat: @"shouyinjia%zi.m4a",currentTime]];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:outPutFilePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:outPutFilePath error:nil];
    }
    
    // 查看当前session支持的fileType类型
    NSLog(@"---%@",[session supportedFileTypes]);
    session.outputURL = [NSURL fileURLWithPath:outPutFilePath];
    session.outputFileType = AVFileTypeAppleM4A; //与上述的`present`相对应
    session.shouldOptimizeForNetworkUse = YES;   //优化网络
    
    [session exportAsynchronouslyWithCompletionHandler:^{
        if (session.status == AVAssetExportSessionStatusCompleted) {
            NSLog(@"合并成功----%@", outPutFilePath);
            [self.soundsArr addObject: outPutFilePath];
            if (!self.player.isPlaying) {
                self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: outPutFilePath] error:nil];
                [self.player play];
                self.player.delegate = self;
                [self.soundsArr removeLastObject];
            }

        } else {
            // 其他情况, 具体请看这里`AVAssetExportSessionStatus`.
        }
    }];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSString * path = player.url.description;
    path = [path stringByReplacingOccurrencesOfString: @"file://" withString: @""];
    if ([[NSFileManager defaultManager] fileExistsAtPath: path]) {
        [[NSFileManager defaultManager] removeItemAtPath: path error:nil];
    }
    if (self.soundsArr.count > 0) {
        self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: [self.soundsArr firstObject]] error:nil];
        [self.player play];
        self.player.delegate = self;
        [self.soundsArr removeObjectAtIndex: 0];
    }
}
- (NSString *)filePath
{
    if (!_filePath) {
        _filePath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
        NSString *folderName = [_filePath stringByAppendingPathComponent:@"MergeAudio"];
        BOOL isCreateSuccess = [kFileManager createDirectoryAtPath:folderName withIntermediateDirectories:YES attributes:nil error:nil];
        if (isCreateSuccess) _filePath = [folderName stringByAppendingPathComponent:@"xindong.m4a"];
    }
    return _filePath;
}
- (NSMutableArray *)soundsArr
{
    if (nil == _soundsArr) {
        _soundsArr = [NSMutableArray new];
    }
    return _soundsArr;
}
@end
